/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2p;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Gatech 
 */
public class Test {

    public static MulticastSocket socket;
    public static  InetAddress red;

    public static void main() throws IOException {
        socket = new MulticastSocket(9000);
        red = InetAddress.getByName("225.4.5.6");
        socket.joinGroup(red);
        hablar h = new hablar();
        h.start();
        //escucharBeta e = new escucharBeta();
        //e.start();
    }

    static class escucharBeta extends Thread {

        public escucharBeta() {
            super();
        }
        byte[] buf = new byte[1000];
        DatagramPacket rec = new DatagramPacket(buf, buf.length);

        public void run() {
            if (!socket.isClosed()) {

                ArrayList<DatagramPacket> r = new ArrayList<DatagramPacket>();
                while (!socket.isClosed()) {
                    try {
                        socket.receive(rec);
                    } catch (IOException ex) {
                        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                    }


                    if (rec.getData() != null) {
                        System.out.println(rec.getData());

                    }

                }
            }
        }
    }

    static class hablar extends Thread {

        public hablar() {
            super();
        }
        byte[] buf = new byte[1000];
        DatagramPacket rec = new DatagramPacket(buf, buf.length);

        public void run() {
            if (!socket.isClosed()) {
                byte[] buf = new byte[1000];
                for (int i = 0; i != 50; i++) {
                    String palabra = "holaaaa " + i;
                    //System.out.print("Voy a enviar... ");
                    buf = palabra.getBytes();
                    DatagramPacket enviar = new DatagramPacket(buf, buf.length, red, 9000);
                    try {
                        socket.send(enviar);
                    } catch (IOException ex) {
                        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }
        }
    }
}
